<?php
	define('BASEPATH', dirname(dirname(__FILE__)));
	require_once('config.php');

	$server 	= $config->database['hostname'];
	$user		= $config->database['username'];
	$password 	= $config->database['password'];
	$database	= $config->database['database'];
	$admin_link = $config->admin_email_link;
		
	$connection = GetConnection();
		
	if (empty($_POST['do'])==FALSE) {
		switch($_POST["do"]){
			
			case "InsertGallery":
					InsertGallery($_POST["authorId"]);
				break;
				
			case "InsertGalleryPhotos":
					InsertGalleryPhotos($_POST["galleryId"],$_POST["fileNames"]);
				break;
				
			case "GetGalleryPhotos":
					if(isset($_POST["first"]) && isset($_POST["last"]) )
					{
						GetGalleryPhotos($_POST["galleryId"],$_POST["first"],$_POST["last"]);
					}else
					{
						GetGalleryPhotos($_POST["galleryId"]);
					}
					
				break;
				
			case "GetGalleryThumbsFor":
					GetGalleryThumbsFor($_POST["galleryId"]);
				break;
				
			case "GetGalleryThumbsWithSearch":
					GetGalleryThumbsWithSearch($_POST["searchTerm"]);
				break;
			
			case "OrderGalleryPhotos":
					OrderGalleryPhotos($_POST["galleryId"],$_POST["orderData"]);
				break;
			
			case "SavePhotoProperties":
					SavePhotoProperties($_POST["photoId"],$_POST["photoTags"],$_POST["photoPublic"]);
				break;
				
			case "RemoveTag":
					RemoveTag($_POST["tagId"]);
				break;
			
			case "MakeGuestCheck":
					MakeGuestCheck($_POST["newfilename"], $_POST["photoName"], $_POST["month"], $_POST["day"], $_POST["year"], $_POST["topText"], $_POST["bottomText"], $_POST["topSize"], $_POST["bottomSize"], $_POST["topColor"], $_POST["bottomColor"]);
				break;
			case "CreateNewPhotographerLogin":
					CreateNewPhotographerLogin($_POST["email"]);
				break;
			
			case "GetPhotographerList":
					GetPhotographerList();
				break;
			
			case "SetPhotographerActiveStatus":
					SetPhotographerActiveStatus($_POST["id"], $_POST["status"]);
				break;
				
			case "Login":
					Login($_POST["email"], $_POST["password"]);
				break;
				
			case "SetPermanentPassword":
					SetPermanentPassword($_POST["email"], $_POST["password"]);
				break;
				
			case "SaveGalleryData":
					//SaveGalleryData($_POST["galleryId"], $_POST["month"], $_POST["day"], $_POST["year"], $_POST['name'],  $_POST['topText'], $_POST['bottomText'], $_POST['topColor'], $_POST['bottomColor']);
					SaveGalleryData($_POST["galleryId"], $_POST["month"], $_POST["day"], $_POST["year"],  $_POST['topText'], $_POST['bottomText']);
				break;
				
			case "GetAllCategories":
					GetAllCategories();
				break;
				
			case "GetCategoryById":
					GetCategoryById($_POST["categoryId"]);
				break;
				
			case "SaveGalleryCategory":
					SaveGalleryCategory($_POST["galleryId"],$_POST["categoryId"]);
				break;
				
			case "SaveNewCategory":
					SaveNewCategory($_POST["title"],$_POST["color"]);
				break;
			case "GetGalleriesByAuthorId":
					GetGalleriesByAuthorId($_POST["authorId"]);
				break;
			case "GetAllGalleries":
					GetAllGalleries();
				break;
			case "GetPublicGalleries":
					GetPublicGalleries();
				break; 
			case "GetPublicGalleriesByCategory":
					GetPublicGalleriesByCategory($_POST["categoryId"]);
				break;
			case "GetGalleryData":
					GetGalleryData($_POST["galleryId"]);
				break;
			
			case "SetGalleryPublicStatus":
					SetGalleryPublicStatus($_POST["galleryId"],$_POST["status"]);
				break;
			
			case "GetPhotoData":
					GetPhotoData($_POST["photoId"]);
				break;
			case "SetGalleryName":
					SetGalleryName($_POST["galleryId"],$_POST["name"]);
				break;
			case "UpdatePhotoPublic":
					UpdatePhotoPublic($_POST["photoId"],$_POST["photoPublic"]);
				break;
		}
	}
	if( isset($GLOBALS["HTTP_RAW_POST_DATA"]) )
	{
		SaveGuestCheckJPG($GLOBALS["HTTP_RAW_POST_DATA"], $_GET["galleryId"]);
	}
		
	mysql_close($connection);
	
	function GetConnection(){
		global $server, $user, $password;
		return mysql_connect($server, $user, $password);
	}
	
	function Query($query){
		global $database, $connection;
		
		mysql_select_db($database, $connection);
		
		$result = mysql_query($query);
		
		if (!$result) {
			$message  = 'Invalid query: ' . mysql_error() . "\n";
			$message .= 'Whole query: ' . $query;
			die($message);
		}
		
		return $result;
	}
	
	function CleanQueryParameter($string, $datatype='string')
	{
		global $connection;
		
		$string = rawurldecode($string);
		
		$string = preg_replace(array("/DELETE/i", "/SELECT/i", "/UPDATE/i","/UNION/i","/INSERT/i","/DROP/i","/http/i","/--/i"), "", $string);
	
	   	$search = array(
		'@&lt;script[^&gt;]*?&gt;.*?&lt;/script&gt;@si',  		// Strip out javascript
		'@&lt;[\/\!]*?[^&lt;&gt;]*?&gt;@si',            			// Strip out HTML tags
		'@&lt;style[^&gt;]*?&gt;.*?&lt;/style&gt;@siU',   		// Strip style tags properly
		'@&lt;![\s\S]*?--[ \t\n\r]*&gt;@'         				// Strip multi-line comments
		);
		$string = preg_replace($search, '', $string);			// Actual filtering
		
		$string = trim($string);								// Strips whitespace (or other characters) from the beginning and end of a string (including NUL-byte)

		if(get_magic_quotes_gpc()){
			$string = stripslashes($string);					// Additional filtering for NUL-byte
		}
		
		if (function_exists('mysql_real_escape_string') AND is_resource($connection))
		{
			$string = mysql_real_escape_string($string, $connection);
		}
		elseif (function_exists('mysql_escape_string'))
		{
			$string = mysql_escape_string($string);
		}
		else
		{
			$string = addslashes($string);
		}
		
		settype($string, $datatype);
		
		return $string;

	}
	
	
	
	function InsertGallery($authorId)
	{
		$query = "INSERT INTO galleries ( author_id, cover_url, name) VALUES ( '$authorId', 'img/guestcheckbase.jpg', 'new gallery' );";
			
		$result = Query($query);
		
		echo mysql_insert_id();
	}	
	
	function InsertGalleryPhotos($galleryId, $names)
	{
		$fileNames = explode(",", $names);
	
		for ($i = 0; $i < count($fileNames); $i++)
		{
			$query = "INSERT INTO photos ( gallery_id, url, position, public ) VALUES ( $galleryId, '{$fileNames[$i]}', '{$i}', '1' );";
			Query($query);
		}
		echo "added $i photos to gallery $galleryId";		
	}
	
	function GetGalleryPhotos($galleryId)
	{
		$numargs = func_num_args();	
		$limit = "";
		if($numargs > 1)
		{
			$arg2 = func_get_arg(1);
			$arg3 = func_get_arg(2);
			$limit = "LIMIT $arg2, $$arg3";
		}
		
		$query = "SELECT * FROM photos WHERE gallery_id = '$galleryId'  ORDER BY position $limit";
		$result = Query($query);
		
		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		echo json_encode($rows);
		
	}
	
	function GetGalleryThumbsFor($galleryId)
	{
		$query = "SELECT * FROM photos WHERE gallery_id = '$galleryId' AND public = '1' ORDER BY position";
		$result = Query($query);
		
		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		
		echo json_encode($rows);
	}
	
	function GetGalleryThumbsWithSearch($searchTerm)
	{
		$query = "SELECT photos.url, photos.id, tags.tag, tags.photo_id FROM photos, tags WHERE tags.photo_id = photos.id AND tags.tag = '$searchTerm' AND public = '1' ORDER BY position";
		$result = Query($query);
		
		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		
		echo json_encode($rows);
	}
	
	function OrderGalleryPhotos($galleryId, $orderData)
	{
		$orderArray = explode(",", $orderData);
		for($i = 0; $i < count($orderArray); $i++)
		{
			$itemOrder = explode(":", $orderArray[$i]);
			$position = $itemOrder[0];
			$photoId = $itemOrder[1];
			
			$query = "UPDATE `photos` SET `position` = $position WHERE `id` = $photoId";
			$result = Query($query);
		}
		
		echo "updated $i photos in gallery $galleryId";
		
	}
	
	function SavePhotoProperties($photoId, $photoTags, $photoPublic)
	{
		if($photoPublic == 'undefined')
		{
			$query = "UPDATE `photos` SET `public` = '0'  WHERE `id` = '$photoId'";
		}else
		{
			$query = "UPDATE `photos` SET `public` = '1'  WHERE `id` = '$photoId'";
		}
		$result = Query($query);
		
		if( strlen( $photoTags) > 0)
		{
			//$photoTags = str_replace(" ", "", $photoTags);
			$photoTagsArr = explode(",", $photoTags);	
			array_walk($photoTagsArr, 'trim_value');

			
			for($i = 0; $i < count($photoTagsArr); $i++)
			{
				$firstQuery = "SELECT * FROM tags WHERE `photo_id`='$photoId' AND `tag`='{$photoTagsArr[$i]}' ";
				$result = Query($firstQuery);
				$num_rows = mysql_num_rows($result);
				
				if($num_rows == 0)
				{
					$query = "INSERT INTO tags ( photo_id, tag ) VALUES ( $photoId, '{$photoTagsArr[$i]}' );";
					Query($query);
				}
				
			}
			
		}
		
		$query = "SELECT * FROM tags WHERE photo_id = '$photoId'";
		$result = Query($query);

		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		echo json_encode($rows);
			
		//echo "SAVED at ". date('h:i:s A');
	}
	
	function RemoveTag($tagId)
	{
		$query = "DELETE FROM tags WHERE id='$tagId'";
		$result = Query($query);
		
		echo "Deleted.";
	}
	
	function trim_value(&$value) 
	{ 
	    $value = trim($value); 
	}
	
	function MakeGuestCheck($newfilename, $photoName, $month, $day, $year, $topText, $bottomText, $topSize=12, $bottomSize=12, $topColor="#000000", $bottomColor="#000000")
	{
	
		//Set the Image source variables
		$backgroundSource = "img/guestcheckbase.jpg";
		$foregroundSource = "photographs/".$photoName.".JPG";
		
		//Create new images
		$outputImage = imagecreatefromjpeg($backgroundSource);
		$foregroundImage = imagecreatefromjpeg($foregroundSource);
		
		$width_orig = imagesx($foregroundImage);
		$height_orig = imagesy($foregroundImage);
		
		$aspect_ratio = (float) $width_orig / $height_orig;
		
	    $thumb_height = 214;//round($thumb_width * $aspect_ratio);
	    
	    $thumb_width = round($thumb_height * $aspect_ratio);//254;
	    
	    $doc_width = 254;
	    
	    $resizedForegroundImage = imagecreatetruecolor($thumb_width, $thumb_height);
	
		imagecopyresampled($resizedForegroundImage, $foregroundImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);
		
		//Merge the two images
		imagecopymerge(	$outputImage,
						$resizedForegroundImage,
						( ($doc_width / 2) - ($thumb_width / 2 )),95,0,0,
						$thumb_width,
						$thumb_height,
						100);
						
		// TEXT STUFF ===================================================================
		
		// date
		$font_file = 'fonts/atwriter.ttf';
		
		$fontColor = hex_to_rgb("#000000",$outputImage);
		
		$topBox = @ImageTTFBBox($topSize,0,$font_file,$topText) ;
		$topWidth = $topBox[2]-$topBox[0];
		
		$bottomBox = @ImageTTFBBox($bottomSize,0,$font_file,$bottomText) ;
		$bottomWidth = $bottomBox[2]-$bottomBox[0];
		
		$dateFontSize = 11;
	
		
		imagefttext($outputImage, $dateFontSize, 0, 13, 25, $fontColor, $font_file, $month);
		imagefttext($outputImage, $dateFontSize, 0, 73, 25, $fontColor, $font_file, $day);
		imagefttext($outputImage, $dateFontSize, 0, 120, 25, $fontColor, $font_file, $year);
		
		
		// titles
		
		
		$font_file = 'fonts/TCS2.ttf';
		$topFontColor = hex_to_rgb($topColor,$outputImage);
		
		$bottomFontColor = hex_to_rgb($bottomColor,$outputImage);
		
		$topText = strtoupper($topText);
		$bottomText = strtoupper($bottomText);
		
		$remove[] = "'";
		$remove[] = '"';
		$remove[] = '!';
		
		$topText = str_replace( $remove, "", $topText );
		$bottomText = str_replace( $remove, "", $bottomText );
		
		$topBox = @ImageTTFBBox($topSize,0,$font_file,$topText) ;
		$topWidth = $topBox[2]-$topBox[0];
		
		$bottomBox = @ImageTTFBBox($bottomSize,0,$font_file,$bottomText) ;
		$bottomWidth = $bottomBox[2]-$bottomBox[0];
	
		
		imagefttext($outputImage, $topSize, 0, ( ($doc_width / 2) - ($topWidth / 2) ), 65, $topFontColor, $font_file, $topText);
		imagefttext($outputImage, $bottomSize, 0, ( ($doc_width / 2) - ($bottomWidth / 2) ), ($thumb_height + 95 + 30), $bottomFontColor, $font_file, $bottomText);
		
		// TEXT STUFF ===================================================================
		
		
		$generatedFileName = "covers/".uniquename("ac_","jpg");	
		
		//save jpg at 90% quality
		imagepng($outputImage,$generatedFileName);
		
		// OR
		
		//Output header and send new image to browser
		//header('Content-type: image/jpg');
		//imagejpeg($outputImage,NULL,90);
		    
		$query = "UPDATE `galleries` SET `cover_url` = '$generatedFileName' WHERE `id` = '$newfilename'";
		$result = Query($query);
		
		imagedestroy($outputImage);
		echo "../".$generatedFileName;
		
	}
	
	function CreateNewPhotographerLogin($to)
	{
		global $admin_link;
		
		$newPassword = createRandomPassword();
		
		// subject
		$subject = 'The Cobra Snake Photographer Login';
		
		
		// message
		$message = '
		<html>
		<head>
		  <title>YOUR LOGIN</title>
		</head>
		<body>
		  <p>Here is your new Password.  Please <a href="'.$admin_link.'">log in</a> and reset it to activate your account.</p>
		  Pass: '.$newPassword.'
		</body>
		</html>
		';
		
		
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		
		// Additional headers
		$headers .= 'To: New Photographer Login <'.$to.'>' . "\r\n";
		$headers .= 'From: The Cobra Snake <admin@thecobrasnake.com>' . "\r\n";

		// Mail it
		mail($to, $subject, $message, $headers);
		
		$newPassword = $newPassword."_temp";

		// save new password
		$query = "SELECT * FROM users WHERE email = '$to' LIMIT 1";
		$result = Query($query);
		$num_rows = mysql_num_rows($result);
				
		if($num_rows == 0)
		{
			$query = "INSERT INTO users ( email, password, active ) VALUES ( '$to', '$newPassword', '1' );";
		}else
		{
			$query = "UPDATE users SET password = '$newPassword', active = '1' WHERE email = '$to'";
		}
		
		Query($query);
		
		echo "Message Sent";
	}
	
	function GetPhotographerList()
	{
		$query = "SELECT * FROM users";
		$result = Query($query);

		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		echo json_encode($rows);
	}
	
	function SetPhotographerActiveStatus($id, $newStatus)
	{
		$query = "UPDATE users SET active = '$newStatus' WHERE id = $id";
		Query($query);
		
		echo "Status Updated";
	}
	
	function SetPermanentPassword($email, $password)
	{
		session_start();
		if(isset($_SESSION['updatable']))
		{
			if($_SESSION['updatable'] == "0313")
			{
				unset($_SESSION['updatable']);
				$query = "UPDATE users SET password = '$password' WHERE email = '$email'";
				Query($query);
				Login($email, $password);
				echo "Password Saved";
			}
			
		}
		
	}
	
	function Login($email, $password)
	{
		$query = "SELECT * FROM users WHERE email='$email' ";
		$result = Query($query);
		
		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		
		
		
		if( count($rows) > 0)
		{
			if($password == $rows[0]['password'] && $rows[0]['active'] == "1")
			{
				$valid = "TRUE";	
				session_start();
				$_SESSION['logged_in'] = "1";
				$_SESSION['authorId'] = $rows[0]['id'];
				if($rows[0]['permission_level'] == '1')
				{
					$_SESSION['logged_in_admin'] = "1";	
				}
			}else if($password."_temp" == $rows[0]['password'])
			{
				$valid = "NEW";
				session_start();
				$_SESSION['updatable'] = "0313";
			}else
			{
				$valid = "FALSE";
			}
					
		}else
		{
			$valid = "NONE";
		}
		
		
		echo $valid;
	}
	
	/*
function SaveGalleryData($galleryId, $month, $day, $year, $name, $topText, $bottomText, $topColor, $bottomColor)
	{
	
		$monthArr=array();
		$monthArr[0]="JAN";
		$monthArr[1]="FEB";
		$monthArr[2]="MAR";
		$monthArr[3]="APR";
		$monthArr[4]="MAY";
		$monthArr[5]="JUN";
		$monthArr[6]="JUL";
		$monthArr[7]="AUG";
		$monthArr[8]="SEP";
		$monthArr[9]="OCT";
		$monthArr[10]="NOV";
		$monthArr[11]="DEC";	
		
		$monthNum = array_search($month,$monthArr) + 1;
		$dateComposite = "20".$year."-".$monthNum."-".$day;
	
		$query = "UPDATE galleries SET date = '$dateComposite', name = '$name', top_text = '$topText', bottom_text='$bottomText', top_color='$topColor', bottom_color='$bottomColor' WHERE id = '$galleryId'";
		Query($query);
		
		echo  "success: ".$query;
	}
*/
	function SaveGalleryData($galleryId, $month, $day, $year, $topText, $bottomText)
	{
	
		$monthArr=array();
		$monthArr[0]="JAN";
		$monthArr[1]="FEB";
		$monthArr[2]="MAR";
		$monthArr[3]="APR";
		$monthArr[4]="MAY";
		$monthArr[5]="JUN";
		$monthArr[6]="JUL";
		$monthArr[7]="AUG";
		$monthArr[8]="SEP";
		$monthArr[9]="OCT";
		$monthArr[10]="NOV";
		$monthArr[11]="DEC";	
		
		$monthNum = array_search($month,$monthArr) + 1;
		$dateComposite = "20".$year."-".$monthNum."-".$day;
	
		$query = "UPDATE galleries SET date = '$dateComposite', top_text = '$topText', bottom_text='$bottomText' WHERE id = '$galleryId'";
		Query($query);
		
		echo  "success: ".$query;
	}
	
	function GetAllCategories()
	{
		$query = "SELECT * FROM categories";
		$result = Query($query);

		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		echo json_encode($rows);
	}
	
	function GetCategoryById($categoryId)
	{
		$query = "SELECT * FROM categories WHERE id='$categoryId'";
		$result = Query($query);

		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		echo json_encode($rows);
	}
	
	function SaveGalleryCategory($galleryId, $categoryId)
	{
		$query = "UPDATE galleries SET category_id = '$categoryId' WHERE id = '$galleryId'";
		Query($query);
		
		echo "success";
	}
	
	function SaveNewCategory($title, $color)
	{
		$query = "INSERT INTO categories ( title, color ) VALUES ( '$title', '$color' );";
			
		$result = Query($query);
		
		echo mysql_insert_id();
	}
	
	function GetGalleriesByAuthorId($authorId)
	{
		$query = "SELECT * FROM users WHERE id = '$authorId' LIMIT 1";
		$result = Query($query);
		$row = mysql_fetch_assoc($result);
		
		if($row['permission_level'] == "1")
		{
			// this is an admin.  get all galleries.
			$query = "SELECT * FROM galleries";
		}else{
			// this is a photographer.  get only his/her galleries.
			$query = "SELECT * FROM galleries WHERE author_id = '$authorId'";
			
		}
	
		$result = Query($query);
	
		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		echo json_encode($rows);
	
		
	}
	
	function GetAllGalleries()
	{
		$query = "SELECT * FROM galleries";
		$result = Query($query);

		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		
		echo json_encode($rows);
	}
	
	function GetPublicGalleries()
	{
		$query = "SELECT * FROM galleries WHERE public='1'";
		$result = Query($query);

		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		
		echo json_encode($rows);
	}
	
	function GetPublicGalleriesByCategory($categoryId)
	{
		$query = "SELECT * FROM galleries WHERE public='1' AND category_id='$categoryId'";
		$result = Query($query);

		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}
		
		echo json_encode($rows);
	}
	
	function GetGalleryData($galleryId)
	{
		$query = "SELECT * FROM galleries WHERE id = '$galleryId' LIMIT 1";
		$result = Query($query);
		
		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}

		echo json_encode($rows);
		
	}
	
	function SetGalleryPublicStatus($galleryId, $status)
	{
		$query = "UPDATE galleries SET public = '$status' WHERE id = '$galleryId'";
		Query($query);
		
		echo "success";
	}
	
	function GetPhotoData($photoId)
	{
		$query = "SELECT * FROM photos WHERE id = '$photoId' LIMIT 1";
		$result = Query($query);
		
		$rows = array();
		while($r = mysql_fetch_assoc($result)) 
		{
			$rows[] = $r;
		}

		echo json_encode($rows);
		
	}
	
	function SaveGuestCheckJPG($rawJPGData, $galleryId)
	{
		$uniqueStamp = date(U);
		$filename = $uniqueStamp.".jpg";
		$fp = fopen( $filename,"wb");
		fwrite( $fp, $rawJPGData );
		fclose( $fp );
		
		rename($filename, "covers/$filename");
		
		$query = "UPDATE `galleries` SET `cover_url` = 'covers/$filename' WHERE `id` = '$galleryId'";
		$result = Query($query);
		
		echo "filename=".$filename;
	}
	
	function SetGalleryName($galleryId, $name)
	{
		$query = "UPDATE `galleries` SET `name` = '$name' WHERE `id` = '$galleryId'";
		$result = Query($query);
		
		echo "success.";
	}
	
	function UpdatePhotoPublic($photoId, $photyoPublic)
	{
		$query = "UPDATE `photos` SET `public` = '$photyoPublic' WHERE `id` = '$photoId'";
		$result = Query($query);
		
		echo "success.";
	}
	
	//  ============================================== UTILITY FUNCITONS ============================================================  
	
	function createRandomPassword() 
	{
	    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
	    srand((double)microtime()*1000000);
	    $i = 0;
	    $pass = '' ;
	    
	    while ($i <= 5) 
	    {
	        $num = rand() % 33;
	        $tmp = substr($chars, $num, 1);
	        $pass = $pass . $tmp;
	        $i++;
	    }
	    return $pass;
	}
	
	function hex_to_rgb($hex, $img)
	{
		$matches = array();
		
		$red = 100;
		$green = 100;
		$blue = 100;
		
		if( preg_match( "/[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i", $hex, $matches ) )
		{
		    $red = hexdec( $matches[1] );
		    $green = hexdec( $matches[2] );
		    $blue = hexdec( $matches[3] );
		}
		
		$text_color = ImageColorAllocate( $img, $red, $green, $blue ); 
	
	    return $text_color;
	}
	function uniquename($prefix,$extension){
		$return='';
		for ($i=0;$i<7;$i++){
			$return.=chr(rand(97,122));
		}
		$return="$prefix-$return-".time()."-X.$extension";	
		return $return;	
	}
	
	
	
	
?>